/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package aso.upna.filesystem;

import aso.upna.cancion.Cancion;
import aso.upna.cancion.CancionLocal;
import aso.upna.playlist.GenericIterator;
import java.io.File;
import java.util.Vector;

/**
 *
 * @author triki
 */

public class SharedFolder {

    private String path;
    private Vector fileList;
    private String extension;
    
    private int n;

    public SharedFolder(String path,String ext)
    {
        fileList = new Vector();
        this.path = new String(path);
        this.extension = new String(ext);
       
        this.loadFilteredList(path);
    }

    public int count_elements()
    {
        return fileList.size();
    }

    private void loadFilteredList(String path_base)
    {
        int i;
        String[] aux;
        File faux = null;
        
        File f = new File(path_base);
        
        if(f == null)
        {
            System.out.println("Petada!");
            return;
        }
        
        aux = f.list();

       /* if(f.isDirectory())
            System.out.println("Es un directorio");
        if(f.canRead())
            System.out.println("Tiene permisos de lectura!");
        System.out.println("array: "+aux.length);*/
        
        for(i=0;i<aux.length;i++)
        {
            faux = new File(path_base+aux[i]);
            if(faux.isDirectory())
            {
                loadFilteredList(path_base+aux[i]+"/");
            }
            if(aux[i].endsWith(extension))
            {
                fileList.add(new CancionLocal(aux[i],path_base));
            }
        }
    }

    public String getPath()
    {
        return path;
    }

    public void refreshList()
    {
        fileList.removeAllElements();
        loadFilteredList(path);
    }

    public void setFilter(String ext)
    {
        extension = new String(ext);
    }

    public void listFiles()
    {
        String aux = null;
        FileIterator fiter = new FileIterator(fileList);

        while(fiter.hasNext())
        {
            System.out.println(""+fiter.current().getFilename());
            fiter.next();
        }
    }

    public boolean searchFile(String filename)
    {
        String aux = null;
        FileIterator fiter = new FileIterator(fileList);

        while(fiter.hasNext())
        {
            aux = fiter.current().getFilename();
            if(aux.regionMatches(false, 0, filename, 0, filename.length()))
                return true;
            fiter.next();
        }
        return false;
    }
    
    public GenericIterator getIterator()
    {
        return new GenericIterator(fileList);
    }
}
